package com.twu.biblioteca.data;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: zgq
 * Date: 13-7-5
 * Time: 下午3:34
 * To change this template use File | Settings | File Templates.
 */
public class UserBase {
    public static final String USER_NOT_EXITS = "Please talk to a Librarian. Thank you.";
    private String bibliotecaUserDataBaseName;


    public UserBase(String dataBaseName) {
        this.bibliotecaUserDataBaseName = dataBaseName;
    }

    public boolean validateUser(String userName, String password) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(new File(bibliotecaUserDataBaseName)));
            String line;
            while((line=reader.readLine())!=null) {
                if(validateUserInLine(userName, password, line)) return true;
            }
            reader.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return false;
    }

    private boolean validateUserInLine(String userName, String password, String line) {
        String[] userInfoItem = line.split("\t");
        if(userInfoItem.length==4) {
             if(userName.equals(userInfoItem[0])&&password.equals(userInfoItem[3])) return true;
        }
        return false;
    }

    public String printUserInfo(String userName) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(new File(bibliotecaUserDataBaseName)));
            String line;
            while((line=reader.readLine())!=null) {
                if(findUserInLine(userName, line)) return userInformationWithoutPasswd(line);
            }
            reader.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return USER_NOT_EXITS;
    }

    private boolean findUserInLine(String userName, String line) {
        String[] userInfoItem = line.split("\t");
        if(userInfoItem.length==4) {
            if(userName.equals(userInfoItem[0])) return true;
        }
        return false;
    }

    private String userInformationWithoutPasswd(String userInfo) {
        return userInfo.substring(0, userInfo.lastIndexOf("\t"));
    }
}
